﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YougeBookmark.Models;
using YougeBookmark.Utilities;

namespace YougeBookmark.Data
{
    public class BookmarkRepository
    {
        private readonly DatabaseContext _context;
        private readonly Logger _logger;

        public IDbContextTransaction BeginTransaction()
        {
            return _context.Database.BeginTransaction();
        }

        public BookmarkRepository(DatabaseContext context, Logger logger)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 创建新书签（自动生成创建时间戳）
        /// </summary>
        public async Task<Bookmark> AddAsync(Bookmark bookmark)
        {
            try
            {
                if (await _context.Bookmarks.AnyAsync(b => b.Url == bookmark.Url))
                {
                    _logger.Warn($"重复URL书签: {bookmark.Url}");
                    return null;
                }

                bookmark.CreatedAt = DateTime.Now;
                _context.Bookmarks.Add(bookmark);
                await _context.SaveChangesAsync();
                return bookmark;
            }
            catch (Exception ex)
            {
                _logger.Error($"书签创建失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 级联删除书签及关联标签
        /// </summary>
        public async Task<bool> DeleteAsync(int bookmarkId)
        {
            try
            {
                var entity = await _context.Bookmarks
                    .Include(b => b.BookmarkTags)
                    .FirstOrDefaultAsync(b => b.Id == bookmarkId);

                if (entity == null) return false;

                _context.Bookmarks.Remove(entity);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error($"书签删除失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 更新可编辑字段（标题/摘要/备注/缩略图）
        /// </summary>
        public async Task<Bookmark> UpdateAsync(Bookmark updated)
        {
            try
            {
                var existing = await _context.Bookmarks.FindAsync(updated.Id);
                if (existing == null) return null;

                existing.Title = updated.Title;
                existing.Summary = updated.Summary;
                existing.Remark = updated.Remark;
                existing.ThumbnailPath = updated.ThumbnailPath;

                await _context.SaveChangesAsync();
                return existing;
            }
            catch (Exception ex)
            {
                _logger.Error($"书签更新失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取完整书签详情（包含关联标签）
        /// </summary>
        public async Task<Bookmark> GetFullByIdAsync(int bookmarkId)
        {
            return await _context.Bookmarks
                .Include(b => b.BookmarkTags)
                .ThenInclude(bt => bt.Tag)
                .FirstOrDefaultAsync(b => b.Id == bookmarkId);
        }

        /// <summary>
        /// 分页复合查询（支持多标签筛选）
        /// </summary>
        public async Task<(List<Bookmark> Items, int Total)> SearchAsync(
            string keyword = null,
            List<int> tagIds = null,
            DateTime? startDate = null,
            DateTime? endDate = null,
            int pageIndex = 0,
            int pageSize = 10)
        {
            try
            {
                var query = _context.Bookmarks
                    .Include(b => b.BookmarkTags)
                    .ThenInclude(bt => bt.Tag)
                    .AsQueryable();

                // 关键词搜索（标题/摘要/备注）
                if (!string.IsNullOrWhiteSpace(keyword))
                {
                    query = query.Where(b =>
                        EF.Functions.Like(b.Title, $"%{keyword}%") ||
                        EF.Functions.Like(b.Summary, $"%{keyword}%") ||
                        EF.Functions.Like(b.Remark, $"%{keyword}%"));
                }

                // 时间范围筛选
                if (startDate.HasValue)
                    query = query.Where(b => b.CreatedAt >= startDate.Value);
                if (endDate.HasValue)
                    query = query.Where(b => b.CreatedAt <= endDate.Value);

                // 多标签联合筛选
                if (tagIds?.Count > 0)
                {
                    query = query.Where(b =>
                        b.BookmarkTags.Any(bt => tagIds.Contains(bt.TagId)));
                }

                // 分页处理
                var total = await query.CountAsync();
                var items = await query
                    .OrderByDescending(b => b.CreatedAt)
                    .Skip(pageIndex * pageSize)
                    .Take(pageSize)
                    .ToListAsync();

                return (items, total);
            }
            catch (Exception ex)
            {
                _logger.Error($"复合查询失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 根据URL精确查找书签
        /// </summary>
        public async Task<Bookmark> GetByUrlAsync(string url)
        {
            return await _context.Bookmarks
                .FirstOrDefaultAsync(b => b.Url == url);
        }

        /// <summary>
        /// 获取最近添加的N条书签
        /// </summary>
        public async Task<List<Bookmark>> GetRecentAsync(int count = 5)
        {
            return await _context.Bookmarks
                .OrderByDescending(b => b.CreatedAt)
                .Take(count)
                .ToListAsync();
        }
    }
}